<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" ref="dataGridRef" @selection-change="handleSelectionChange" showSelection>
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.productKey" placeholder="产品名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-tree-select
                                    placeholder="产品标签"
                                    v-model="queryData.labels"
                                    :data="labelTree"
                                    :props="defaultProps"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    check-strictly
                                    :render-after-expand="false"
                                    show-checkbox
                                    clearable
                                    node-key="labelNo"
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-input v-model="queryData.objectDisplayName" placeholder="产品模型" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select placeholder="集成状态" v-model="queryData.integrationEnable" clearable>
                                    <el-option
                                        v-for="(value, key) in IntegrationEnable"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select placeholder="集成方式" v-model="queryData.integrationMethod" clearable>
                                    <el-option
                                        v-for="(value, key) in IntegrationMethod"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button
                        type="primary"
                        plain
                        @click="onEnable()"
                        :disabled="enabledTableSelectId && enabledTableSelectId.length ? false : true"
                        >启用</el-button
                    >
                    <el-button
                        @click="onDisable()"
                        :disabled="disableTableSelectId && disableTableSelectId.length ? false : true"
                        >停用</el-button
                    >
                    <el-button
                        type="primary"
                        @click="onSet()"
                        :disabled="enabledTableSelectId && enabledTableSelectId.length ? false : true"
                        >设置</el-button
                    >
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="产品名称" width="300" fixed show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-button link type="primary" @click="onGoDetail(row)">
                            {{ row.productName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="productNo" label="标识符" show-overflow-tooltip />
                <el-table-column label="产品标签" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.labelNames ? row.labelNames.join('；') : '' }}
                    </template>
                </el-table-column>
                <el-table-column prop="objectDisplayName" label="模型名称" show-overflow-tooltip />
                <el-table-column prop="integratorName" label="集成者" show-overflow-tooltip />
                <el-table-column label="集成方式">
                    <template #default="{ row }">
                        {{ IntegrationMethod[row.integrationMethod] }}
                    </template>
                </el-table-column>
                <el-table-column label="集成状态">
                    <template #default="scope">
                        <span class="table-item-status" :status="IntegrationEnable[scope.row.integrationEnable]">
                            {{ IntegrationEnable[scope.row.integrationEnable] }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="135" fixed="right">
                    <template #default="{ row }">
                        <el-button link type="primary" @click="onDisable(row)" v-if="row.integrationEnable">
                            停用
                        </el-button>
                        <template v-else>
                            <el-button link type="primary" @click="onEnable(row)"> 启用 </el-button>
                            <el-button link type="primary" @click="onSet(row)"> 设置 </el-button>
                        </template>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { messageProductService, runLabelService } from '@great/services';
import { useRouter } from 'vue-router';
import { checkPermi } from '@/utils/ruoyi';
import { showPopupBox } from '@great/utils';
import { IntegrationMethod } from '@/utils/constant';
import Set from './components/list/Set.vue';
import { DataGrid, Block, type DataGridInstance } from '@great/components';

enum IntegrationEnable {
    true = '启用',
    false = '停用'
}
const router = useRouter();
// 查询条件
const queryData = ref({
    productKey: '',
    labels: [],
    objectDisplayName: '',
    integrationMethod: '',
    integrationEnable: ''
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const labelTree = ref();
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await messageProductService.getPage({
            current,
            size,
            ...queryData.value,
            labels: queryData.value.labels ? queryData.value.labels.join(',') : null
        });
        return { data: res.data.records, total: res.data.total };
    }
});

// 表格勾选数据
const tableSelect = ref<unknown[]>([]);
const enabledTableSelectId = ref<string[]>([]);
const disableTableSelectId = ref<string[]>([]);
const enabledTableSelect = ref<string[]>([]);
// 表格勾选
const handleSelectionChange = (val: unknown[]) => {
    tableSelect.value = val;
    enabledTableSelectId.value = [];
    disableTableSelectId.value = [];
    enabledTableSelect.value = [];
    val.forEach((item: any) => {
        if (item.integrationEnable) {
            disableTableSelectId.value.push(item.productNo);
        } else {
            enabledTableSelectId.value.push(item.productNo);
            enabledTableSelect.value.push(item);
        }
    });
};
// 查看详情
const onGoDetail = (row: { id: string }) => {
    if (checkPermi(['iot:product:detail'])) {
        router.push({
            name: 'IoT-product-detail',
            params: {
                id: row?.id
            }
        });
    }
};
// 设置
const onSet = (row?: any) => {
    if (row) {
        showPopupBox(Set, {
            row,
            callBack: dataGridRef.value?.refresh
        });
    } else {
        if (disableTableSelectId.value && disableTableSelectId.value.length) {
            ElMessageBox.confirm(`仅对所选“停用”状态产品进行设置！`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    showPopupBox(Set, {
                        row: enabledTableSelect.value,
                        callBack: dataGridRef.value?.refresh
                    });
                })
                .catch(() => {});
        } else {
            showPopupBox(Set, {
                row: enabledTableSelect.value,
                callBack: dataGridRef.value?.refresh
            });
        }
    }
};
// 停用
const onDisable = async (row?: { productName: string; productNo: string }) => {
    ElMessageBox.confirm(`确认启用${row ? row.productName : ''}产品集成`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await messageProductService.disable(row ? [row.productNo] : disableTableSelectId.value);
            ElNotification({
                title: '停用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 启用
const onEnable = async (row?: { productName: string; productNo: string }) => {
    ElMessageBox.confirm(`确认启用${row ? row.productName : ''}产品集成`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await messageProductService.enable(row ? [row.productNo] : enabledTableSelectId.value);
            ElNotification({
                title: '启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-producctLabel' });
    labelTree.value = res.data;
};
getLabelTree();
</script>

<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='停用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
